<?php

/*
|--------------------------------------------------------------------------
| Application Routes
|--------------------------------------------------------------------------
|
| Here is where you can register all of the routes for an application.
| It's a breeze. Simply tell Laravel the URIs it should respond to
| and give it the controller to call when that URI is requested.
|
*/


Route::get('/', function () {
    return view('welcome');
});

//前台路由组

//后台路由组
Route::group(['prefix'=>'admin', 'middleware'=>'login'], function(){

	//加载后台主页
	Route::resource('index', 'Admin\IndexController');
    Route::get('logout', 'Admin\IndexController@logout');
    Route::post('dologin', 'Admin\IndexController@doLogin');

	//加载用户模块的路由
	Route::resource('users', 'Admin\UsersController');
	//在资源控制器中添加额外的路由
    Route::get('user/trash', 'Admin\UsersController@trash');
    Route::get('user/trash/del', 'Admin\UsersController@del');
    Route::get('user/trash/recover', 'Admin\UsersController@recover');

	Route::controller('cates', 'Admin\CatesController');

	Route::controller('articles', 'Admin\ArticlesController');

    Route::controller('goods', 'Admin\GoodsController');

});

// 前台路由
Route::group(['prefix'=>'home'], function(){

    Route::controller('index', 'Home\IndexController');
    Route::controller('list', 'Home\ListController');
    Route::controller('detail', 'Home\DetailController');
    Route::controller('user', 'Home\UserController');
    Route::controller('order', 'Home\OrderController');

});



Route::any('/login', function (){

    if(Request::session()->has('uid')){
        return redirect('admin/index');
    }

    if (Request::getMethod() == 'POST')
    {
        $rules = ['captcha' => 'required|captcha'];
        $validator = Validator::make(Input::all(), $rules);
        if ($validator->fails())
        {
            echo "<script>alert('抱歉，验证码错误！');window.location.href='login';</script>";
        }
        else
        {
            //验证用户名与密码信息
            $nickname=Request::input('username');
            $password=Request::input('password');

            //判断用户是否存在
            $res = DB::select('select * from users where username=?',[$nickname]);

            if(empty($res)){
                echo "<script>alert('抱歉，用户名不存在！');window.location.href='login';</script>";
            }
            if(Hash::check($password,$res[0]['password'])){

                Request::session()->put('uid',$res[0]['id']);
                Request::session()->put('uname',$res[0]['username']);
                echo "<script>alert('恭喜，登陆成功！');window.location.href='admin/index';</script>";
            }else{
                echo "<script>alert('抱歉，密码错误！');window.location.href='login';</script>";

            }
        }
    }

    return view('Admin/Index/Login');

});
